var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
const mfs = require('./mfs');
const utils = require('./utils');

let src = "";
function generator(config) {
    let pack_type = config.hotDebug ? "debug" : "release"
    let hotVersion = config.hotDebug ? config.hotVersionDebug : config.hotVersion
    const verPath = getVerPath(hotVersion);
    const title = config.title;
    let downloadUrl = `${config.hotUrl}/${pack_type}/versions`
    let manifest = {
        version: hotVersion,
        packageUrl: `${downloadUrl}/${verPath}/`,
        remoteManifestUrl: `${downloadUrl}/${verPath}/project.manifest`,
        remoteVersionUrl: `${downloadUrl}/${verPath}/version.manifest`,
        assets: {},
        searchPaths: []
    };
    
    console.log("==version:", manifest.version);
    console.log("==packageUrl:", manifest.packageUrl);
    console.log("==remoteManifestUrl:", manifest.remoteManifestUrl);
    console.log("==remoteVersionUrl:", manifest.remoteVersionUrl);
    src = config.nativePath;
    let dest = `${config.hotOutPath}/${pack_type}/${verPath}`;
    let gitDest = `${config.hotGitPath}/${pack_type}/${verPath}`;
    console.log("==src:", src);
    console.log("==dest:", dest);
    console.log("==gitDest:", gitDest);
    console.log("==manifest:", JSON.stringify(manifest));

    mfs.rm(path.join(dest));
    mfs.mkdir(path.join(dest));
    mfs.mkdir(path.join(dest, 'src'));
    mfs.mkdir(path.join(dest, 'assets'));


    // Iterate assets and src folder
    readDir(path.join(src, 'src'), manifest.assets);
    readDir(path.join(src, 'assets'), manifest.assets);

    var destManifest = path.join(dest, 'project.manifest');
    var destVersion = path.join(dest, 'version.manifest');

    mfs.writeFile(destManifest, JSON.stringify(manifest));
    console.log('Manifest successfully generated');
    delete manifest.assets;
    delete manifest.searchPaths;
    mfs.writeFile(destVersion, JSON.stringify(manifest));
    console.log('Version successfully generated');

    mfs.cp(path.join(src, 'src'), path.join(dest, 'src'))
    mfs.cp(path.join(src, 'assets'), path.join(dest, 'assets'))

    if (!config.hotDebug) {
        console.log("==================上传热更新版本到git资源库==================")
        mfs.mkdir(path.join(gitDest));
        mfs.mkdir(path.join(gitDest, 'src'));
        mfs.mkdir(path.join(gitDest, 'assets'));
        mfs.cp(path.join(dest), path.join(gitDest))        
        const push_package = `cd ${config.hotGitPath} && git add . && git commit -m "更新${pack_type}版本 版本号: ${hotVersion}" && git push origin master`;
        // utils.runShSync(push_package);
        console.log("==================上传热更新版本到git资源库完成==================")
    }
    console.log('copy file successfully generated');

    let configData = {
        version: hotVersion,
        url: downloadUrl
    }
    console.log("------------------------------------------------------------------------------------------")
    console.log("-------------------------------------热更新资源导出结束--------------------------------------")
    // console.log(`--------${config.hotDebug ? "测试环境" : "正式环境"}--热更新配置:----------------`)
    // console.log(JSON.stringify(configData));
    console.log("------------------------------------------------------------------------------------------")
    return configData;
}

function isMac() {
    return true;
}
/**@description 上传热更新资源 */
function uploadToOss(config) {
    const pack_type = config.hotDebug ? "debug" : "release";
    const version = config.hotDebug ? config.hotVersionDebug : config.hotVersion;
    const uri = `${pack_type}/${getVerPath(version)}`
    const is_mac = isMac() ? "./oss_upload/ossutilmac64" : "./oss_upload/ossutil64.exe";
    // const manifest_path = `oss://bubuduo-guesssong/games_assets_update/g1/${pack_type}/${config.title}/versions/${getVerPath(version)}`;
    const manifest_path = `${config.oss}/${config.title}/${pack_type}/versions/${getVerPath(version)}`;
    const pack_path = `${manifest_path}`;
    const mac = is_mac
    // assets 
    const res_path = `${config.hotOutPath}/${uri}`;
    console.log("\n本地资源地址 = ", res_path);
    console.log("\n热更新版本远程资源地址 = ", pack_path);
    
    const upload_res_import = `${mac} cp ${res_path} ${pack_path}/ --recursive -f -u --config-file ./oss_upload/.ossutilconfig`;
    console.log("开始打上传打包资源");
    console.log(upload_res_import);
    utils.runShSync(upload_res_import);
    console.log("热更新资源更新完成");

    // 上传打包的资源到制定的git仓库
    // console.log("上传打包的资源到制定的git仓库");
    // try{
    //     upload_package(pack_type, version);
    // }catch(e){
    //     console.log("上传包的错误信息 ",e);
    // }
    console.log("上传打包资源完成");
}

function getVerPath(hotVersion) {
    const arr = hotVersion.split('.')
    return `ver_${arr[0]}_${arr[1]}`
}

function readDir(dir, obj) {
    var stat = fs.statSync(dir);
    if (!stat.isDirectory()) {
        return;
    }
    let subpaths = fs.readdirSync(dir), subpath, size, md5, compressed, relative;
    for (var i = 0; i < subpaths.length; ++i) {
        if (subpaths[i][0] === '.') {
            continue;
        }
        subpath = path.join(dir, subpaths[i]);
        stat = fs.statSync(subpath);
        if (stat.isDirectory()) {
            readDir(subpath, obj);
        }
        else if (stat.isFile()) {
            // Size in Bytes
            size = stat['size'];
            md5 = crypto.createHash('md5').update(fs.readFileSync(subpath)).digest('hex');
            compressed = path.extname(subpath).toLowerCase() === '.zip';

            relative = path.relative(src, subpath);
            relative = relative.replace(/\\/g, '/');
            relative = encodeURI(relative);
            obj[relative] = {
                'size': size,
                'md5': md5
            };
            if (compressed) {
                obj[relative].compressed = true;
            }
        }
    }
}


function startPack(config) {
    let configData = generator(config);
    return configData;
}

module.exports.startPack = startPack;
module.exports.uploadToOss = uploadToOss;